package com.woniu.mealsService.consumer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.woniu.exception.meals.FeignException;
import com.woniu.exception.meals.OrderException;
import com.woniu.mealsService.mapper.OrderLogMapper;
import com.woniu.mealsService.mapper.OrderProductMapper;
import com.woniu.mealsService.model.OrderProduct;
import com.woniu.mealsService.service.OrderProductService;
import com.woniu.user.client.UserFeignClient;
import com.woniu.user.dto.UserInfoFeignDto;
import com.woniu.utils.EnumException;
import com.woniu.utils.Result;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author jiang
 */
@Component
public class OrderConsumer {
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private OrderProductMapper orderProductMapper;
    @Autowired
    private UserFeignClient userFeignClient;
    @RabbitListener(bindings = @QueueBinding(
        value =@Queue(name = "listener_Order"),
        exchange =@Exchange(name = "delay_Update_take"),
        key = "order"
    ))
    @RabbitHandler
    // 商家手动接单时，超时未接单
    public void listenerOrder(String orderId) throws Exception{
        try {
            LambdaQueryWrapper<OrderProduct> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderProduct::getOrderId,orderId);
            OrderProduct orderProduct = orderProductMapper.selectOne(queryWrapper);
            if (null == orderProduct){
                throw new OrderException(EnumException.ORDER_NULL_EXCEPTION);
            }
            Result<UserInfoFeignDto> userInfo = userFeignClient.getUserInfo(orderProduct.getUserId());
            if (userInfo.getCode()!=200){
                throw new FeignException(EnumException.NET_ERROR_EXCEPTION);
            }
            String roleId = userInfo.getData().getRoleId();
            if (7 == orderProduct.getOrderState()){
                orderProductService.cancelOrder(orderId,orderProduct.getUserId(),roleId);
            }
        }catch (Exception e){
            throw e;
        }
    }
}
